package cc.miwuya.owner.service.impl;

import cc.miwuya.common.util.exception.HubException;
import cc.miwuya.owner.domain.Orders;
import cc.miwuya.owner.mapper.OrdersMapper;
import cc.miwuya.owner.service.OrdersService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author 杩烽浘妫灄
 * @description 针对表【order(支付订单表)】的数据库操作Service实现
 * @createDate 2024-02-22 20:13:04
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {
    @Value("${alipay.server-url}")
    String alipayServerUrl;
    @Value("${alipay.appid}")
    String alipayAppid;
    @Value("${alipay.private-key}")
    String alipayPrivateKey;
    @Value("${alipay.public-key}")
    String alipayPublicKey;
    @Value("${alipay.notify-url}")
    String alipayNotifyUrl;
    @Value("${alipay.return-url}")
    String alipayReturnUrl;

    @Override
    public Object getPage(Page page, String name, Long userId) {
        Page<Orders> ordersPage;
        if (StrUtil.isEmpty(name)) {
            ordersPage = page(page, new QueryWrapper<Orders>().eq("user_id", userId));
        } else {
            ordersPage = page(page, new QueryWrapper<Orders>().eq("user_id", userId).like("item", name));
        }

        return ordersPage;
    }

    @Override
    public Object getTollManOrderList(Page page, String name, Long tollManId) {
        Page<Orders> ordersPage;
        if (StrUtil.isEmpty(name)) {
            ordersPage = page(page, new QueryWrapper<Orders>().eq("tollman", tollManId));
        } else {
            ordersPage = page(page, new QueryWrapper<Orders>().eq("tollman", tollManId).like("item", name));
        }
        return ordersPage;
    }

    @Override
    public Object pay(Long orderSn, String payType) {
        Orders shopOrder = getById(orderSn);
        return alipay(shopOrder, payType);
    }


    @Override
    public Object payCheck(Long orderSn) {
        Orders shopOrder = getById(orderSn);
        if (shopOrder.getStatus() == 2) {
            //已经支付成功
            return "success";
        }
        AlipayTradeQueryResponse response = aliCheck(shopOrder.getOutOrderId());
        if (response.isSuccess()) {
            String tradeStatus = response.getTradeStatus();
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                Orders sn = getById(orderSn);
                if (sn.getStatus() == 1) {
                    sn.setStatus(2);
                    updateById(sn);
                    return "success";
                }
            }
        }
        return "fail";
    }

    private AlipayTradeQueryResponse aliCheck(String orderSn) {

        DefaultAlipayClient alipayClient = new DefaultAlipayClient(alipayServerUrl, alipayAppid, alipayPrivateKey, "json", "UTF-8", alipayPublicKey,
                "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orderSn);
        request.setBizContent(jsonObject.toString());
        try {
            return alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new HubException("查询异常，请稍后在世");
        }
    }

    private String alipay(Orders shopOrder, String payType) {
        System.out.println(payType);
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(alipayServerUrl, alipayAppid, alipayPrivateKey, "json", "UTF-8", alipayPublicKey, "RSA2");
        System.out.println(shopOrder);
        if (payType.equals("APP")) {
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            request.setNotifyUrl(alipayNotifyUrl);
            request.setReturnUrl(alipayReturnUrl + "?id=" + shopOrder.getId());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no", shopOrder.getOutOrderId());
            jsonObject.put("total_amount", shopOrder.getAmount());
            jsonObject.put("subject", shopOrder.getItem());
            jsonObject.put("product_code", "QUICK_WAP_WAY");
            jsonObject.put("time_expire", DateUtil.formatLocalDateTime(LocalDateTime.now().plusHours(1)));
            System.out.println(jsonObject.get("product_code"));
            request.setBizContent(jsonObject.toString());
            AlipayTradeWapPayResponse pageExecute = null;
            try {
                pageExecute = alipayClient.pageExecute(request);
                return pageExecute.getBody();
            } catch (AlipayApiException e) {
                throw new HubException("支付异常");
            }
        } else {
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(alipayNotifyUrl);
            request.setReturnUrl(alipayReturnUrl + "?id=" + shopOrder.getId());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no", shopOrder.getOutOrderId());
            jsonObject.put("total_amount", shopOrder.getAmount());
            jsonObject.put("subject", shopOrder.getItem());
            jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
            jsonObject.put("time_expire", DateUtil.formatLocalDateTime(LocalDateTime.now().plusHours(1)));
            System.out.println(jsonObject.get("product_code"));
            request.setBizContent(jsonObject.toString());
            AlipayTradePagePayResponse pageExecute = null;
            try {
                pageExecute = alipayClient.pageExecute(request);
                return pageExecute.getBody();
            } catch (AlipayApiException e) {
                throw new HubException("支付异常");
            }
        }
    }

}




